<template>
  <div class="main1">
    <el-card>
      <div class="codiv">
        <div>
          <el-form :inline="true">
            <el-form-item>
              <el-input placeholder="请输入课程" @keyup.enter.native="seachEnter" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
                >搜 索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button type="success" class="cobutton" @click="exportData"
            >导 出 数 据</el-button
          >
          <el-button type="success" class="cobutton" @click="handleAdd"
            >添 加 课 程</el-button
          >
        </div>
      </div>
    </el-card>

    <el-card>
      <el-table :data="tbData" border style="width: 100%" v-loading="loading">
        <el-table-column
          label="Id"
          prop="id"
          width="50"
          v-if="false"
        ></el-table-column>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="课程名称" align="center" prop="courseName">
        </el-table-column>
        <el-table-column label="教材名" align="center" prop="textBookName">
        </el-table-column>
        <el-table-column
          label="是否为公共课"
          align="center"
          prop="isPublicCourses"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.isPublicCourses ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="专业序号" align="center" prop="specializedNum">
        </el-table-column>
        <el-table-column label="任课老师" align="center" prop="teacherName">
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-dialog title="新增或编辑课程" :visible.sync="dialogFormVisible">
          <el-form :model="form" :rules="rules" ref="formDemo" class="cofrom">
            <el-form-item
              label="课程名称:"
              :label-width="formLabelWidth"
              prop="courseName"
            >
              <el-input v-model="form.courseName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="教材名:"
              :label-width="formLabelWidth"
              prop="textBookName"
            >
              <el-select v-model="form.textBookId" placeholder="请选择教材名">
                <el-option
                  v-for="(item, index) in bookInfo"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="是否公共课:"
              :label-width="formLabelWidth"
              prop="isPublicCourses"
            >
              <el-switch
                v-model="form.isPublicCourses"
                active-text="是"
                inactive-text="否"
              ></el-switch>
            </el-form-item>
            <el-form-item
              label="专业序号:"
              :label-width="formLabelWidth"
              prop="specializedNum"
            >
              <el-input
                v-model="form.specializedNum"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="任课老师:"
              :label-width="formLabelWidth"
              prop="teacherName"
            >
              <el-select v-model="form.teacherId" placeholder="请选择任课老师">
                <el-option
                  v-for="(item, index) in teacherInfo"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="handleSave">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <div class="block">
        <el-pagination
          class="defenye"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageIndex"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.count"
          background
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
import * as XLSX from "xlsx/xlsx.mjs";
import { GetMaterialList } from "@/api/materialapi";
import { GetTeacherList } from "@/api/teacherapi";
import {
  getCourseList,
  addCourse,
  editCourse,
  delCourse,
} from "@/api/courseapi";
export default {
  data() {
    return {
     
      teacherInfo: [],
      bookInfo: [],
      keyword: "",
      formLabelWidth: "120px",
      page: {
        pageIndex: 1, // 当前页面
        pageSize: 10, // 每页展示列表数
        count: 0, // 课程列表总数
      },
      // 表单验证规则
      rules: {
        courseName: [
          {
            required: true,
            trigger: "blur",
            message: "请输入课程名称",
          },
        ],
        specializedNum: [
          {
            required: true,
            trigger: "blur",
            message: "请输入专业序号",
          },
        ],
      },
      loading: false,
      tbData: [],
      dialogFormVisible: false,
      form: {
        id: 0,
        courseName: "",
        specializedNum: "",
        teacherId: "",
        isPublicCourses: "",
        textBookId: "",
      },
      currentIndex: 0,
    };
  },
  mounted() {
    this.GetTeacher();
    this.GetMaterial();
    this.GetList();
  },
  methods: {
     seachEnter(e){
        var keyword =window.event ?e.keyword :e.which;
        if(keyword === keyword){
          this.GetList()
        }
      },
    GetMaterial() {
      GetMaterialList().then((res) => {
        res.data.forEach((item) => {
          var obj = {
            label: item.textBookName,
            value: item.id,
          };
          this.bookInfo.push(obj);
        });
      });
    },
    GetTeacher() {
      // 获取所有教师信息
      GetTeacherList().then((res) => {
        // console.log(res);
        res.data.forEach((item) => {
          var obj = {
            label: item.teacherInfo.teacherName,
            value: item.teacherInfo.workNumber,
          };
          this.teacherInfo.push(obj);
        });
      });
    },
    // 拉取后台数据（带分页）
    GetList() {
      let params = {
        keyword: this.keyword,
        pageIndex: this.page.pageIndex,
        pageSize: this.page.pageSize,
      };
      this.tbData = [];
      getCourseList(params).then((res) => {
        console.log(res);
        res.data.forEach((item) => {
          var obj = {
            id: item.course.id,
            courseName: item.course.courseName,
            specializedNum: item.course.specializedNum,
            isPublicCourses: item.course.isPublicCourses,
            textBookName: item.textBook.textBookName,
            teacherName: item.teacher.teacherName,
            textBookId:item.textBook.id,
            teacherId:item.teacher.workNumber
          };
          this.tbData.push(obj);
          this.page.count = res.page.count;
        });
      });
    },
    // 搜索
    handleQuery() {
      this.GetList();
      this.$message.success("查找成功")
    },
    // 新增
    handleAdd() {
      this.dialogFormVisible = true;
      this.form.id = 0;
      this.form.courseName = "";
      this.form.specializedNum = "";
      this.form.isPublicCourses = false;
      this.form.teacherId = "";
      this.form.textBookId = "";
    },
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      console.log(row);
      this.form.id = row.id;
      this.form.textBookId = row.textBookId;
      this.form.courseName = row.courseName;
      this.form.specializedNum = row.specializedNum;
      this.form.teacherId = row.teacherId;
      this.form.isPublicCourses = row.isPublicCourses;
      this.currentIndex = index;

      console.log(this.form);
    },
    // 页面页码改变时，重新拉取数据
    handleCurrentChange(val) {
      this.page.pageIndex = val > 0 ? val : 1;
      this.GetList();
    },
    // 页面大小改变时，重新拉取数据
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.GetList();
    },
    // 删除
    handleDelete(index, row) {
      // 删除时获得当前表数组中的下标
      this.currentIndex = index;
      // 弹框提示
      this.$confirm("此操作将永久删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          delCourse(row.id).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg);
              this.$router.go(0);
            } else {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 取消
    handleCancel() {
      this.dialogFormVisible = false;
    },

    // 保存
   handleSave() {
      this.$refs.formDemo.validate(async (valid) => {
        console.log(this.form);
        if (!valid) return;
        // 如果表单中的id为0，则认为是添加用户，反之则为修改用户
        if (this.form.id === 0) {
          addCourse(this.form)
            .then((res) => {
              console.log(res);
              if (res.code === 200) {
                //将新添加的数据push到现有表数据的最后面
                this.tbData.push(res.data);
                this.$message.success(res.msg);
                this.GetList();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
          this.dialogFormVisible = false;
        } else {
          editCourse(this.form.id, this.form)
            .then((res) => {
              console.log(res);
                this.tbData.splice(this.currentIndex, 1, res.data);
                this.$message.success(res.msg);
                this.GetList();
            })
            .catch((err) => {
              console.log(err);
            });
          this.dialogFormVisible = false;
        }
      });
    },
    // 导出数据
    exportData() {
      const headers = [
        {
          title: "课程名称",
          key: "courseName",
        },
        {
          title: "教材名",
          key: "textBookName",
        },
        {
          title: "是否为公共课",
          key: "isPublicCourse",
        },
        {
          title: "专业序号",
          key: "specializedNum",
        },
        {
          title: "任课老师",
          key: "teacherName",
        },
      ];
      this.exportExcel(headers, this.tbData, "课程表.xlsx");
    },
    exportExcel(headers, data, fileName = "导出结果.xlsx") {
      const _headers = headers
        .map((item, i) =>
          Object.assign(
            {},
            {
              key: item.key,
              title: item.title,
              position: String.fromCharCode(65 + i) + 1,
            }
          )
        )
        .reduce(
          (prev, next) =>
            Object.assign({}, prev, {
              [next.position]: { key: next.key, v: next.title },
            }),
          {}
        );
      const _data = data
        .map((item, i) =>
          headers.map((key, j) =>
            Object.assign(
              {},
              {
                content: item[key.key],
                position: String.fromCharCode(65 + j) + (i + 2),
              }
            )
          )
        )
        // 对刚才的结果进行降维处理（二维数组变成一维数组）
        .reduce((prev, next) => prev.concat(next))
        // 转换成 worksheet 需要的结构
        .reduce(
          (prev, next) =>
            Object.assign({}, prev, { [next.position]: { v: next.content } }),
          {}
        );
      // 合并 headers 和 data
      console.log(_data);
      const output = Object.assign({}, _headers, _data);
      // 获取所有单元格的位置
      const outputPos = Object.keys(output);
      // 计算出范围 ,["A1",..., "H2"]
      const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;

      // 构建 workbook 对象
      const wb = {
        SheetNames: ["mySheet"],
        Sheets: {
          mySheet: Object.assign({}, output, {
            "!ref": ref,
            "!cols": [
              { wpx: 45 },
              { wpx: 100 },
              { wpx: 200 },
              { wpx: 80 },
              { wpx: 150 },
              { wpx: 100 },
              { wpx: 300 },
              { wpx: 300 },
            ],
          }),
        },
      };
      // console.log(wb);
      // 导出 Excel
      XLSX.writeFile(wb, fileName);
    },
  },
};
</script>
<style>
.codiv {
  display: flex;
  float: left;
}
.cobutton {
  margin-top: 1px;
}
.cofrom > .el-form-item > .el-form-item__label {
  font-weight: bolder !important;
  font-size: 18px;
}
.block {
  margin-top: 30px;
  margin-bottom: 10px;
}
</style>